
//
//  WaitOrderViewController.m
//  ShangAPP
//
//  Created by macpro on 16/1/23.
//  Copyright © 2016年 wangdao. All rights reserved.
//

#import "WaitOrderViewController.h"
#import "OrderTableViewCell.h"
#import "MyTools.h"
#import "OrderMessageViewController.h"
#import "AddMapViewController.h"
#import <MJRefresh.h>
#import "Model.h"
@interface WaitOrderViewController ()<UITableViewDataSource,UITableViewDelegate>

@end

@implementation WaitOrderViewController
{
    UITableView *_myTab;
    NSMutableArray *_dataarr;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    _myTab = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 160)];
    _myTab.separatorStyle = UITableViewCellSeparatorStyleNone;
    _myTab.showsVerticalScrollIndicator = NO;
    _myTab.backgroundColor = UIColorFromRGB(0xEBEBEB);
    _myTab.delegate = self;
    _myTab.dataSource = self;
//    UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"denglu_bg.png"]];
//    [_myTab setBackgroundView:backgroundView];
    [_myTab addGifHeaderWithRefreshingTarget:self refreshingAction:@selector(downMJ)];

    [self setExtraCellLineHidden:_myTab];
    [self.view addSubview:_myTab];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tongzhi:) name:@"tongzhi1" object:nil];
    
}
- (void)tongzhi:(NSNotification *)text{
    
    if ([text.userInfo[@"one"] integerValue] == 2) {
        [self downMJ];
    }
}
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"tongzhi1" object:nil];
}


//下拉刷新
-(void)downMJ
{
    [self requesttableview];
    [_myTab reloadData];
    [_myTab.header endRefreshing];
}

- (void)requesttableview
{
    
    _dataarr = [[NSMutableArray alloc]init];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    NSString *urlstr = @"http://www.xsy777.com/app/b_send/myorderps.html";
    NSDictionary *dic = @{@"page":@"1"};
    if ([user objectForKey:@"token"]) {
        dic = @{@"page":@"1",
                @"user_token":[user objectForKey:@"token"],
                @"type":@"3"};
    }
    AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [manager POST:urlstr parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        if ([[responseObject objectForKey:@"status"]intValue] == 1) {
            for (NSDictionary *dic in [responseObject objectForKey:@"data"]) {
                Model *model=[[Model alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                //追加数据
                [_dataarr addObject:model];
            }
            [_myTab reloadData];
        }else{
            [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
        }
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if ([MyTools connectedToNetwork] == 0) {
            [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
        }else{
            [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
        }
    }];
}

#pragma mark tableview代理

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataarr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 180;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    OrderTableViewCell *cell = [_myTab cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[OrderTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    Model*model=_dataarr[indexPath.row];
    
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    //名字
    if (model.name) {
        cell.name.text =model.name;
    }else{
        //        cell.name.text = _dataarr[indexPath.row][@"name"];
        cell.name.text =@" ";
    }
    
    CGSize namesize = CGSizeMake(WIDTH-80, 20);
    NSDictionary * ndic = [NSDictionary dictionaryWithObjectsAndKeys:cell.name.font,NSFontAttributeName,nil];
    CGSize  actualnamesize =[cell.name.text boundingRectWithSize:namesize options:NSStringDrawingUsesLineFragmentOrigin  attributes:ndic context:nil].size;
    cell.name.frame = CGRectMake(80,6, actualnamesize.width, actualnamesize.height);
    cell.phoneNum.frame = CGRectMake(90+actualnamesize.width, 5, 100, 20);
    
    //电话
    if (model.phone) {
        cell.phoneNum.text =model.phone;
    }else{
        //        cell.phoneNum.text = _dataarr[indexPath.row][@"phone"];
        cell.phoneNum.text =@"";
    }
    
    
    
    //地址
    if (model.address) {
        cell.address.text =model.address;
    }else{
        //        cell.address.text = _dataarr[indexPath.row][@"address"];
        cell.address.text =@" ";
    }
    
    CGSize addsize = CGSizeMake(WIDTH - 90, 50);
    NSDictionary * addtdic = [NSDictionary dictionaryWithObjectsAndKeys:cell.address.font,NSFontAttributeName,nil];
    CGSize  addactualsize =[cell.address.text boundingRectWithSize:addsize options:NSStringDrawingUsesLineFragmentOrigin  attributes:addtdic context:nil].size;
    cell.address.frame = CGRectMake(80,35, addactualsize.width, addactualsize.height);
    
    
    
    if (model.payment) {
        cell.moneyLeb.text = [NSString stringWithFormat:@"￥%@ (%@)",model.count_price,model.payment];
    }else{
        cell.moneyLeb.text = [NSString stringWithFormat:@"￥%@",model.count_price];
        
    }
    
    
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:cell.moneyLeb.text];
    NSRange monRange = NSMakeRange([[noteStr string] rangeOfString:[NSString stringWithFormat:@"(%@)",model.payment]].location, [[noteStr string] rangeOfString:[NSString stringWithFormat:@"(%@)",model.payment]].length);
    [noteStr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xff9800) range:monRange];
    
    NSRange monRange1 = NSMakeRange([[noteStr string] rangeOfString:[NSString stringWithFormat:@"(%@)",model.send_type]].location, [[noteStr string] rangeOfString:[NSString stringWithFormat:@"(%@)",model.send_type]].length);
    [noteStr addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xff9800) range:monRange1];
    
    [cell.moneyLeb setAttributedText:noteStr];
    
    
    //时间
    if (model.create_time) {
        cell.timeLab.text =[NSString stringWithFormat:@"%@",model.create_time];
    }else{
        cell.timeLab.text =@"";
    }
    
    if ([model.content isEqualToString:@""]) {
        cell.otherLab.text =@"无";
    }else{
        cell.otherLab.text =[NSString stringWithFormat:@"%@",model.content];
    }
    
    
    
    UIButton *peiBut;

    
    if (!peiBut) {
        peiBut = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH-90, 125, 80, 25)];
    }
    peiBut.layer.cornerRadius = 5;
    peiBut.layer.borderColor =(__bridge CGColorRef _Nullable)([UIColor clearColor]);
    [peiBut setBackgroundColor:UIColorFromRGB(0xe51c23)];
    peiBut.titleLabel.font = [UIFont systemFontOfSize:14];
    peiBut.tag = indexPath.row;
    
    if ([model.status isEqual:@"3"]){
        
        [peiBut setTitle:@"确认配送" forState:UIControlStateNormal];
        [peiBut setBackgroundColor:UIColorFromRGB(0xe51c23)];
        [peiBut addTarget:self action:@selector(peiBut:) forControlEvents:UIControlEventTouchUpInside];
        cell.stateimage.image = [UIImage imageNamed:@"待派送"];
    }else{
        
        [peiBut setTitle:@"已调度" forState:UIControlStateNormal];
        [peiBut setBackgroundColor:UIColorFromRGB(0xcecece)];
        cell.stateimage.image = [UIImage imageNamed:@"已调度"];
    }
    [cell addSubview:peiBut];
     
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //[self requetPei:_dataarr[indexPath.row][@"id"]];
    OrderMessageViewController * vc =[[OrderMessageViewController alloc]init];
    Model *mode = _dataarr[indexPath.row];
    vc.idStr =mode.id;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)peiBut:(UIButton *)but
{
    Model*model=_dataarr[but.tag];
    [self requetPei:model.id];

}

- (void)requetPei:(NSString *)uid
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *urlstr = @"http://www.xsy777.com/app/b_send/peisongs.html";
    
    NSDictionary *dic = @{@"user_token":[user objectForKey:@"token"],
                          @"id":uid};
    NSLog(@"%@",dic);
    AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [manager POST:urlstr parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        NSLog(@"%@",[responseObject objectForKey:@"info"]);
        
        [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
        [self downMJ];
        } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
            if ([MyTools connectedToNetwork] == 0) {
                [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
            }else{
                [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
            }
    }];
}

- (void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self downMJ];
}
@end
